import * as factory from "@/plugins/z-dragxml/factory";


export function initTplComponents(state) {
  let app = getApp();

  function getTplComponents(group = undefined) {
    return state.components.filter(v => {
      // console.log('v', v)
      return v.DRAG_GROUP === group
    })
  }


  // console.log( getTplComponents('high'))

  function reloadTplComponents() {
    /**
     * 初始化拖拽组件
     * @type {{name, label: string}[]}
     */
    state.components = [
      ...app.get_custom_components(
        function ([comName, comDef]) {
          return comDef.ZDragXmlCom
        }
      ).filter(v => {
        if (v?.origin?.NOT_IN_GROUP) {
          return false
        }
        return true
      }).map(v => {
        // console.log(v)
        let extDataset = {}
        if (v.origin && v.origin.DRAG_DATASET) {
          extDataset = v.origin.DRAG_DATASET()
        }
        let label = v.label ?? ''
        if (v.origin && v.origin.DRAG_LABEL_XML) {
          label = v.origin.DRAG_LABEL_XML()
        }
        // console.log(ret)
        return {
          name: v.value,
          DRAG_GROUP: v.origin.DRAG_GROUP,
          label: label,
          ...extDataset
        }
      })
    ]

    state.tplComponents[0] = {
      label: '基础控件',
      components: getTplComponents()
    }
    state.tplComponents[1] = {
      label: '高级控件',
      components: getTplComponents('high')
    }
    state.tplComponents[2] = {
      label: '第三方控件',
      components: getTplComponents('custom')
    }
    // console.log('reloadTplComponents', state.tplComponents[2])
  }

  reloadTplComponents();

  /**
   * 加载plugin
   * @param p {Prmoise<any>}
   */
  function loadPlugin(p) {
    return new Promise(resolve => {
      p.then(res => {
        // console.log(res)
        res.install({
          register(def) {
            let com = def(factory);
            CustomVueComponent.register(com);
            setTimeout(() => {
              reloadTplComponents();
              resolve()
            }, 300)
          }
        })
      })
    })
  }

  window.__loadPlugin__ = loadPlugin


  return {
    getTplComponents,
    loadPlugin,
    reloadTplComponents
  }
}
